package com.lemon.components.ant.project.makeservice.beanparser;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.swing.JOptionPane;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lemon.components.ant.project.beans.ColumnInfo;
import com.lemon.components.ant.project.beans.ModelInfo;
import com.lemon.components.ant.util.ConfigUtil;
import com.lemon.components.ant.util.PathUtil;
import com.lemon.components.ant.util.TemplateUtil;
import com.lemon.components.common.result.ResultBase;
import com.lemon.ui.codemaker.component.RecentlyFile;
import com.system.core.security.NameUtil;

public class JsonParser {

	private List<ModelInfo> innerClassList = new ArrayList<>();
	
	public ResultBase doParse(String srcstring, String remarkString, ModelInfo beanInfo) {
		ResultBase result = new ResultBase();
		Map<String, RemarkGetter.RemarkInfo> remarksMap = null;
		if(StringUtils.isNotBlank(remarkString)) {
			remarksMap = new HashMap<>();
			String[] remark1 = remarkString.split("\n");
			for (String string : remark1) {
				String[] remark2 = string.split("\t");
				RemarkGetter.RemarkInfo remarkInfo = new RemarkGetter.RemarkInfo();
				remarkInfo.setRemark(remark2[1].trim());
				if (remark2.length > 2 && StringUtils.isNotBlank(remark2[2])) {
					remarkInfo.setReqired(Boolean.valueOf(remark2[2].trim()));
				}
				remarksMap.put(remark2[0].trim(), remarkInfo);
			}
		}
		Object tmp1 = null;
		try {
			tmp1 = JSON.parse(srcstring);
		} catch (Exception e) {
			JOptionPane.showMessageDialog(null, e.getMessage(), "JSON转换错误", JOptionPane.ERROR_MESSAGE);
		}
		if (tmp1 instanceof JSONObject) {
			makeClazz((JSONObject) tmp1, remarksMap, beanInfo);
			makeFile(beanInfo);
			result.setMessage("代码生成成功");
			result.setSuccess(true);
		} else if (tmp1 instanceof JSONArray) {
			System.out.println("数组");
		}

		return result;
	}

	private ModelInfo hasModel(String modalNameString) {
		for (ModelInfo modelInfo : innerClassList) {
			if(modelInfo.getBeanName().equalsIgnoreCase(modalNameString)) {
				return modelInfo;
			}
		}
		ModelInfo modelInfo = new ModelInfo();
		modelInfo.setBeanName(modalNameString);
		innerClassList.add(modelInfo);
		return modelInfo;
	}
	
	public void makeClazz(JSONObject jsonObject, Map<String, RemarkGetter.RemarkInfo> remamrks, ModelInfo beanInfo) {
		ArrayList<ColumnInfo> columns = new ArrayList<>();
		String name = beanInfo.getBeanName();
		
		/**
		 * 循环第x层属性
		 */
		for (Iterator<String> iterator = jsonObject.keySet().iterator(); iterator.hasNext();) {
			
			String key = iterator.next();
			Object value = jsonObject.get(key);
			ColumnInfo columnInfo = new ColumnInfo();
			columnInfo.setColumnCode(key);
			columnInfo.setJavaCode(NameUtil._2JavaName(key));
			// 如果从外部获取注释不为空才设置注释
			if (remamrks != null) {
				columnInfo.setNullAble(remamrks.get(key).isReqired());
				columnInfo.setColumnRemark(remamrks.get(key).getRemark());
			}
			
			// 如果有下级属性并且是对象：1、新建内部内。2、进入下级对象。
			if (value!=null && value.getClass().getName().equalsIgnoreCase("com.alibaba.fastjson.JSONObject")) {
				
				columnInfo.setJavaType(StringUtils.capitalize(NameUtil._2JavaName(key)));
				
				// 如果包含对象，新建个内部内
				ModelInfo innerClass = hasModel(StringUtils.capitalize(NameUtil._2JavaName(key)));
				makeClazz((JSONObject) value, remamrks, innerClass);
				
			// 如果有下级属性并且是数组：1、选取第一个对象新建内部内。2、进入下级对象。
			} else if (value!=null && value.getClass().getName().equalsIgnoreCase("com.alibaba.fastjson.JSONArray")
					&& ((JSONArray) value).size() > 0) {

				ModelInfo innerClass = hasModel(StringUtils.capitalize(NameUtil._2JavaName(key)));
				
				// 如果数组里面没有嵌套数组
				if (((JSONArray) value).get(0) instanceof JSONObject) {
					columnInfo.setJavaType("List<"+StringUtils.capitalize(NameUtil._2JavaName(key))+">");
					makeClazz(((JSONArray) value).getJSONObject(0), remamrks, innerClass);
				
				// 如果数组里面还嵌套了数组
				} else {
					StringBuilder javaTypeBuilder = new StringBuilder("List<");
					javaTypeBuilder.append(((JSONArray) value).get(0).getClass().getSimpleName());
					javaTypeBuilder.append(">");
					columnInfo.setJavaType(javaTypeBuilder.toString());
					removeModal(StringUtils.capitalize(NameUtil._2JavaName(key)));
				}
			
			// 没有下级属性：直接设置基本类型
			} else {
				
				columnInfo.setJavaType(value==null?"Object":value.getClass().getName());
				
			}
			
			columns.add(columnInfo);
			
		}
		beanInfo.setInnerClass(innerClassList);
		beanInfo.setBeanName(name);
		beanInfo.setColumns(columns);
	}
	
	public void makeFile(ModelInfo beanInfo) {
		PathUtil pathUtil = PathUtil.getInstance(ConfigUtil.getInstance(RecentlyFile.configFilePath).getProjectInfo());
		beanInfo.setBeanPath(
				pathUtil.getJavaSourcePath(beanInfo.getMavenModel()).getPath() + beanInfo.getBeanPackage().replaceAll("\\.", "/") + "/"
						+ StringUtils.capitalize(beanInfo.getBeanName()) + ".java");
		TemplateUtil.getInstance(ConfigUtil.getInstance(RecentlyFile.configFilePath).getProjectInfo().getTemplatePath())
				.build("/maven-project-template/service/beans/JSONBeanTemplate.java", beanInfo.getBeanPath(), beanInfo);
	}

	private boolean removeModal(String modalNameString) {
		return innerClassList.removeIf(item->item.getBeanName().equalsIgnoreCase(modalNameString));
	}
}
